package com.q.tqb.activity.send;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewTextChangeEvent;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.q.tqb.R;
import com.q.tqb.adapter.ImagePickerAdapter;
import com.q.tqb.adapter.MySpinnerAdapter;
import com.q.tqb.base.AppConst;
import com.q.tqb.base.BaseActivity;
import com.q.tqb.luban.Luban;
import com.q.tqb.luban.OnCompressListener;
import com.q.tqb.model.BalanceInfo;
import com.q.tqb.model.Packet_numInfo;
import com.q.tqb.model.SpinnerInfo;
import com.q.tqb.model.WxPayData;
import com.q.tqb.util.LogUtil;
import com.q.tqb.util.SPUtil;
import com.q.tqb.util.StringUtil;
import com.q.tqb.util.http.IRawResponse;
import com.q.tqb.util.http.IResponse;
import com.q.tqb.util.http.OkHttpUtil;
import com.q.tqb.util.oss.OssCallback;
import com.q.tqb.util.oss.OssService;
import com.q.tqb.view.GlideLoader;
import com.q.tqb.view.dialog.PayDialog;
import com.q.tqb.view.dialog.PayPassDialog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


public class SendImageActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener, AdapterView.OnItemSelectedListener {


    @BindView(R.id.et_money)
    EditText mEtMoney;
    @BindView(R.id.et_reward_money)
    EditText mEtRewardMoney;
    @BindView(R.id.et_amount)
    EditText mEtAmount;
    @BindView(R.id.rv_select_map)
    RecyclerView mRvSelectMap;
    @BindView(R.id.bt_send)
    Button mBtSend;
    @BindView(R.id.et_quesiton)
    EditText mEtQuesiton;
    @BindView(R.id.et_answer)
    EditText mEtAnswer;
    @BindView(R.id.et_tro)
    EditText mEtTro;
    @BindView(R.id.st_show)
    Switch mStShow;
    @BindView(R.id.st_tweeter)
    Switch mStTweeter;
    @BindView(R.id.et_url)
    EditText mEtUrl;

    @BindView(R.id.spinner)
    AppCompatSpinner spinner;

    private ArrayList<ImageItem> selImageList;
    private ArrayList<ImageItem> images;


    private ImagePickerAdapter adapter;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private int maxImgCount = 3;               //允许选择图片最大数

    private int uid;

    private int payType;
    private String myMoney;
    private String orderId;
    private String payPass;
    private PayDialog payDialog;

    private String address;
    private MyBroadcastReceiver mBroadcastReceiver;
    private int imageAmount = 0;


    private MySpinnerAdapter spinnerAdapter;
    /**
     * 当前选中
     */
    private SpinnerInfo spinnerInfo;
    /**
     * 服务端返回的红包个数信息
     */
    private Packet_numInfo info;

    @Override
    public int getLayoutId() {
        return R.layout.activity_send_image;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        setTitle("发问答红包");
        selImageList = new ArrayList<>();
        mEtMoney.requestFocus();
        adapter = new ImagePickerAdapter(this, selImageList, 3);
        adapter.setOnItemClickListener(this);

        uid = (int) SPUtil.get(this, "uid", 0);
        address = SPUtil.getString(this, "address");
        mRvSelectMap.setLayoutManager(new GridLayoutManager(this, 3));
        mRvSelectMap.setHasFixedSize(true);
        mRvSelectMap.setAdapter(adapter);


        getMoney();
        initReceiver();
        initImagePicker();

        mEtAmount.setEnabled(false);
        spinnerAdapter = new MySpinnerAdapter(this);
        spinner.setOnItemSelectedListener(this);
        getBankArea();

        final int INTERVAL = 800; //输入时间间隔为300毫秒

        RxTextView.textChangeEvents(mEtMoney)
                .debounce(INTERVAL, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TextViewTextChangeEvent>() {


                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) {
                        getPacketNum();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void getMoney() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));
        //  mProgressDialog.show();
        OkHttpUtil.getInstance().post(this, AppConst.URL_GET_MONEY, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                // mProgressDialog.dismiss();
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                BalanceInfo balanceInfo = gson.fromJson(result, BalanceInfo.class);
                myMoney = balanceInfo.getBalance();

                SPUtil.put(SendImageActivity.this, "withdraw", myMoney);
                // mTvMineMoney.setText("¥" + money);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                myMoney = SPUtil.getString(SendImageActivity.this, "withdraw");
                //  mProgressDialog.dismiss();
            }
        });
    }

    private void initReceiver() {
        mBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConst.PAY_IMAGE);
        registerReceiver(mBroadcastReceiver, intentFilter);
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideLoader());
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(false);
        imagePicker.setSaveRectangle(true);
        imagePicker.setSelectLimit(9);
    }

    @OnClick({R.id.iv_back, R.id.bt_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.bt_send:
                String packetMoney = mEtMoney.getText().toString();
                String packetAmount = mEtAmount.getText().toString();
                String packetTitle = mEtQuesiton.getText().toString();
                String getSecret = mEtAnswer.getText().toString();
                if (TextUtils.isEmpty(packetMoney) || TextUtils.isEmpty(packetAmount) || TextUtils.isEmpty(packetTitle) || TextUtils.isEmpty(getSecret)) {
                    showToast("请完整红包信息");
                    return;
                }
                if (selImageList.size() == 0) {
                    showToast("请选择图片");
                    return;
                }
                double money = Double.valueOf(packetMoney);
                int amount = Integer.valueOf(packetAmount);

                if (mStTweeter.isChecked()) {
                    if (money * 0.92 < amount) {
                        showToast("推客专区红包平均金额不小于1元");
                        return;
                    }
                }
                compressImage();
                break;
            default:
                break;
        }
    }

    private void sendRed() {
        imageAmount = 0;
        String packetMoney = mEtMoney.getText().toString();
        String rewardMoney = mEtRewardMoney.getText().toString();

        final double allMoney;
        if (TextUtils.isEmpty(rewardMoney)) {
            allMoney = Double.valueOf(packetMoney);
        } else {
            allMoney = Double.valueOf(packetMoney) + Double.valueOf(rewardMoney);
        }
        payDialog = new PayDialog(SendImageActivity.this, allMoney, myMoney);
        payDialog.setOnSettingListener(new PayDialog.CommonListener() {
            @Override
            public void onClick(int type) {
                if (type == 1) {
                    payType = 3;
                    PayPassDialog payPassDialog = new PayPassDialog(SendImageActivity.this, allMoney, 1);
                    payPassDialog.show();
                    showInputMethod();
                    payPassDialog.setOnSettingListener(new PayPassDialog.CommonListener() {
                        @Override
                        public void onClick(String pass) {
                            payPass = pass;
                            payOrder();
                        }
                    });

                } else {
                    payType = 2;
                    payOrder();
                }
            }
        });
        payDialog.show();
    }


    private void showInputMethod() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 100);
    }

    private void payOrder() {
        String packetMoney = mEtMoney.getText().toString();
        String rewardMoney = mEtRewardMoney.getText().toString();
        String packetAmount = mEtAmount.getText().toString();
        String packetTitle = mEtQuesiton.getText().toString();
        String getSecret = mEtAnswer.getText().toString();
        String packetContent = mEtTro.getText().toString();
        String url = mEtUrl.getText().toString();

        int size = selImageList.size();
        String images = "";
        for (int i = 0; i < size; i++) {
            images = String.format("%s%s;", images, AppConst.OSS_URL + selImageList.get(i).getUpName());
        }
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("packet_money", packetMoney);
        map.put("reward_money", rewardMoney);
        map.put("packet_num", packetAmount);
        map.put("packet_title", packetTitle);
        map.put("get_secret", getSecret);
        map.put("content_link", url);
        map.put("packet_address", address);
        map.put("packet_content", packetContent);
        map.put("packet_type", "2");
        if (mStTweeter.isChecked()) {
            map.put("packet_level", "2");
        } else {
            map.put("packet_level", "1");
        }
        AppConst.ORDER_TYPE = 2;
        map.put("pay_type", payType + "");
        if (payType == 3) {
            map.put("pay_password", payPass);
        }
        map.put("packet_picture", images);
        if (mStShow.isChecked()) {
            map.put("is_show_list", "1");
        } else {
            map.put("is_show_list", "0");
        }
        LogUtil.i(map.toString());
        mProgressDialog.show();
        OkHttpUtil.getInstance().post(this, AppConst.URL_SEND_PACKET, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                mProgressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(element.toString());
                    orderId = jsonObject.getString("order_id");
                    if (payType == 3) {
                        showToast("红包发送成功！");
                        finish();
                    } else if (payType == 2) {
                        wxPay();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                showToast(errorMsg);
                mProgressDialog.dismiss();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    private void wxPay() {
        Map<String, String> map = new HashMap<>();
        map.put("order_id", orderId);
        LogUtil.i(map.toString());
        mProgressDialog.show();
        OkHttpUtil.getInstance().post(this, AppConst.URL_WX_PAY, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                mProgressDialog.dismiss();
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                WxPayData wxPayData = gson.fromJson(element, WxPayData.class);
                IWXAPI api = WXAPIFactory.createWXAPI(SendImageActivity.this, AppConst.WEIXIN_APP_ID);
                api.registerApp(AppConst.WEIXIN_APP_ID);
                PayReq payReq = new PayReq();
                payReq.appId = AppConst.WEIXIN_APP_ID;
                payReq.partnerId = wxPayData.getPartnerid();
                payReq.prepayId = wxPayData.getPrepayid();
                payReq.packageValue = "Sign=WXPay";
                payReq.nonceStr = wxPayData.getNoncestr();
                payReq.timeStamp = "" + wxPayData.getTimestamp();
                payReq.sign = wxPayData.getSign();
                api.sendReq(payReq);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
                mProgressDialog.dismiss();
            }
        });
    }


    class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            payDialog.dismiss();
            finish();
        }
    }

    private void selectDialog() {
        final String[] items = {"相机拍照", "相册选择"};
        AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(SendImageActivity.this);
        singleChoiceDialog.setTitle("选择方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                            Intent intent = new Intent(SendImageActivity.this, ImageGridActivity.class);
                            // 是否是直接打开相机
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
                            startActivityForResult(intent, REQUEST_CODE_SELECT);
                        } else {
                            ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                            Intent intent1 = new Intent(SendImageActivity.this, ImageGridActivity.class);
                            /* 如果需要进入选择的时候显示已经选中的图片，
                             * 详情请查看ImagePickerActivity
                             * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                            startActivityForResult(intent1, REQUEST_CODE_SELECT);
                        }
                        dialog.dismiss();
                    }
                });
        singleChoiceDialog.show();
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                selectDialog();
                break;
            default:
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        }
    }


    private void compressImage() {
        int size = selImageList.size();
        mProgressDialog.show();
        for (int i = 0; i < size; i++) {
            String path = Environment.getExternalStorageDirectory() + "/tqb/tqb_" + i + ".jpg";
            String upPointName = "image/" + uid + "_" + System.currentTimeMillis() + ".JPEG";
            selImageList.get(i).setCompressName(path);
            selImageList.get(i).setUpName(upPointName);

            Luban.with(this)
                    .load(selImageList.get(i).path)
                    .setTargetDir(path)
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(File file) {
                            uPImage(file.getPath());
                            //           LogUtil.i("file.getPath()" + file.getPath());
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                        }
                    }).launch();    //启动压缩
        }

    }


    private void uPImage(String absolutePath) {
        int index = getImageData(absolutePath);
        if (index == -1) {
            showToast("数据混乱");
            return;
        }
        ImageItem imageItem = selImageList.get(index);
        OssService.asyncPutFile(imageItem.getUpName(), imageItem.getCompressName(), new OssCallback(new Handler(), new IRawResponse() {
            @Override
            public void onSuccess(String response) {
                imageAmount++;
                if (imageAmount == selImageList.size()) {
                    mProgressDialog.dismiss();
                    sendRed();
                }

            }

            @Override
            public void onFailure(String errorMsg) {
                showToast("请检查您的网络");
                imageAmount = 0;
                LogUtil.i(errorMsg);
            }
        }));
    }

    private int getImageData(String absolutePath) {

        int size = selImageList.size();
        ImageItem imageItem;
        for (int i = 0; i < size; i++) {
            imageItem = selImageList.get(i);
            if (imageItem.getCompressName().equals(absolutePath)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        spinnerInfo = (SpinnerInfo) spinnerAdapter.getItem(position);
        getPacketNum();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    private void getBankArea() {
        Map<String, String> map = new HashMap<>();

        OkHttpUtil.getInstance().post(this, AppConst.URL_GET_BANK_AREA, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                ArrayList<SpinnerInfo> list = gson.fromJson(result, new TypeToken<ArrayList<SpinnerInfo>>() {
                }.getType());
                spinnerAdapter.setData(list);
                spinner.setAdapter(spinnerAdapter);
//                spinnerAdapter.
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
            }
        });
    }

    private void getPacketNum() {
        double ss = 0;
        try {
            ss = Double.parseDouble(mEtMoney.getText().toString());
        } catch (Exception e) {

        }
        if (ss <= 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("packet_money", mEtMoney.getText().toString());
        map.put("packet_level", spinnerInfo.level);
        OkHttpUtil.getInstance().post(this, AppConst.URL_PACKET_NUM, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                info = gson.fromJson(result, Packet_numInfo.class);
                mEtAmount.setText(info.suggest);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
            }
        });
    }
}

